package com.halixun.d2app.ui;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.halixun.d2app.R;
import com.halixun.d2app.adapter.FootTypeAdapter;
import com.halixun.d2app.base.BaseActivity;
import com.halixun.d2app.base.BasePrintInfo;
import com.halixun.d2app.base.BaseResult;
import com.halixun.d2app.bean.FoodCategoryInfo;
import com.halixun.d2app.bean.print.NetPrintInfo;
import com.halixun.d2app.bean.print.UsbPrintInfo;
import com.halixun.d2app.dialog.IntervalTimeFragment;
import com.halixun.d2app.net.CreateRequestEntity;
import com.halixun.d2app.net.errer.ResultVerifier;
import com.halixun.d2app.utils.DensityUtil;
import com.halixun.d2app.utils.RequestDataUtils;
import com.halixun.d2app.utils.SystemUtil;
import com.halixun.d2app.utils.VersionUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PrintSettingActivity extends BaseActivity implements FootTypeAdapter.FootTypeListener {

    public static final String KEY_PARAMS = PrintSettingActivity.class.getSimpleName() + "key_params";

    public static final String KEY_RETURN_INFO = PrintSettingActivity.class.getSimpleName() + "key_return_info";

    public static final int REQUEST_CODE_PRINT_SETTING_USB = 1045;

    public static final int REQUESTcODE_PRINT_SETTING_NET = 1046;

    private RadioGroup smallTicketGroup;

    private RadioGroup mRadioGroup;

    private TextView intervalTime;

    private IntervalTimeFragment dialog;

    private BasePrintInfo mPrintInfo;

    private RecyclerView mRecyclerView;

    private TextView tvPrintInfo;

    private List<FoodCategoryInfo> mFoodCategoryInfos;

    private FootTypeAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_print_setting);
        mPrintInfo = (BasePrintInfo) getIntent().getSerializableExtra(KEY_PARAMS);
        hideActionBar();
        initView();
        setListeners();
        setAdapter();
        initData();
        getFoodTypes();
    }

    private void setAdapter() {
        mFoodCategoryInfos = new ArrayList<>();
        mAdapter = new FootTypeAdapter(mFoodCategoryInfos);
        mAdapter.setOnFootTypeListener(this);
        mRecyclerView.setAdapter(mAdapter);
    }


    @SuppressLint("NewApi")
    private void getFoodTypes() {
        CreateRequestEntity.getWebService().getFoodTypes(RequestDataUtils.getRequestDataParam(this)).enqueue(new Callback<BaseResult<List<FoodCategoryInfo>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<FoodCategoryInfo>>> call, Response<BaseResult<List<FoodCategoryInfo>>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    mFoodCategoryInfos.addAll(response.body().Data);
                    if (null != mPrintInfo.mFoodCategoryInfos) {
                        for (FoodCategoryInfo info : mPrintInfo.mFoodCategoryInfos) {
                            for (FoodCategoryInfo categoryInfo : response.body().Data) {
                                if (info.getClassName().equals(categoryInfo.getClassName()) && info.getID() == categoryInfo.getID()) {
                                    categoryInfo.setSelected(true);
                                }
                            }
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                } else {
                    ResultVerifier.serceErrers(response);
                }
            }

            @Override
            public void onFailure(Call<BaseResult<List<FoodCategoryInfo>>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
            }
        });
    }


    private void initData() {
        smallTicketGroup.check(mPrintInfo.isPrint ? R.id.smallTicketYes : R.id.smallTicketNo);
        mRadioGroup.check(mPrintInfo.isFractionToPrint ? R.id.fractionPrint : R.id.JewelsPrint);
        intervalTime.setText("分式打印间隔时间(" + mPrintInfo.fractionToPrintIntervalTime + ")");

        String type = mPrintInfo.type == BasePrintInfo.NET_PRINT ? "【网络打印机】" : "【USB打印机】";
        String printName = " ——" + (mPrintInfo.type == BasePrintInfo.NET_PRINT ? ((NetPrintInfo) mPrintInfo).ip + ":" + ((NetPrintInfo) mPrintInfo).port : ((UsbPrintInfo) mPrintInfo).name + "(" + ((UsbPrintInfo) mPrintInfo).id + ")");

        String text = type + printName;
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#444444")), 0, type.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#AAAAAA")), type.length(), text.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvPrintInfo.setText(spannableString);
    }

    private void setListeners() {
        smallTicketGroup.setOnCheckedChangeListener((group, checkedId) -> {
            mPrintInfo.isPrint = checkedId == R.id.smallTicketYes;
            setReturnData();
        });
        mRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            mPrintInfo.isFractionToPrint = checkedId == R.id.fractionPrint;
            intervalTime.setVisibility(mPrintInfo.isFractionToPrint ? View.VISIBLE : View.GONE);
            setReturnData();
        });
        intervalTime.setOnClickListener(v -> {
            if (null == dialog) {
                dialog = new IntervalTimeFragment();
                dialog.setIntervalTimeListener(time -> {
                    mPrintInfo.fractionToPrintIntervalTime = time;
                    intervalTime.setText("分式打印间隔时间(" + time + ")");
                    setReturnData();
                });
            }
            dialog.show(getSupportFragmentManager(), "IntervalTimeFragment");
        });
        findViewById(R.id.exit).setOnClickListener(v -> finish());
    }

    private void initView() {
        smallTicketGroup = findViewById(R.id.smallTicketGroup);
        mRadioGroup = findViewById(R.id.mRadioGroup);
        intervalTime = findViewById(R.id.intervalTime);
        mRecyclerView = findViewById(R.id.mRecyclerView);
        mRecyclerView.setNestedScrollingEnabled(false);
        tvPrintInfo = findViewById(R.id.tvPrintInfo);
    }


    public void setReturnData() {
        Intent data = new Intent();
        data.putExtra(KEY_RETURN_INFO, mPrintInfo);
        setResult(RESULT_OK, data);
    }

    @Override
    public void onFootTypeListener(int position) {
        mPrintInfo.mFoodCategoryInfos = getSelectedType();
        setReturnData();
    }

    public List<FoodCategoryInfo> getSelectedType() {
        List<FoodCategoryInfo> list = new ArrayList<>();
        for (FoodCategoryInfo info : mFoodCategoryInfos) {
            if (info.isSelected()) {
                list.add(info);
            }
        }
        return list;
    }
}
